package com.ysd.service.scheduled;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ysd.service.bean.ClockInteractionBean;
import com.ysd.service.config.MqttConfig;
import com.ysd.service.entity.Weather;
import com.ysd.service.enums.ClockInteractionEnum;
import com.ysd.service.gateway.WeatherAPIClient;
import com.ysd.service.service.ClockService;
import com.ysd.service.service.WeatherService;
import com.ysd.service.util.DateUtil;
import com.ysd.service.util.MqttMessageUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.*;

/**
 * 定时类      设备端可以获取IP城市，可以根据城市获取天气信息，所以定时器不开启
 **/
@Component
@Configuration      //1.主要用于标记配置类，兼备Component的效果。
@EnableScheduling   // 2.开启定时任务
@Slf4j
public class ClockPushScheduled {

    @Autowired
    private ClockService clockService;

    @Autowired
    private WeatherService weatherService;

    @Autowired
    private WeatherAPIClient weatherAPIClient;

    @Autowired
    private MqttConfig mqttConfig;

    @Autowired
    private MqttMessageUtil mqttMessageUtil;

    /*
    * 天气信息获取    每天4点执行
    * 查询所有闹钟的地址，获取这些城市的天气信息，保存到天气信息表】
    * */
//    @Scheduled(cron = "0 0 4 * * ?")
    public void getWeatherScheduled() throws Exception {
        log.info("获取天气信息定时器执行开始时间:{}", DateTime.now());

        // 查询闹钟表里所有的城市地址
        List<String> cityList = clockService.queryClockCitys();

        // 清空之前的数据，插入新查到的数据
        weatherService.deleteWeatherTemp();

        // 查询这些地址的天气，把天气插入天气表
        cityList.forEach(city -> {
            // 发送请求
            try {
                weatherAPIClient.fetchAndSaveWeather(city);
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        });

        log.info("获取天气信息定时器执行结束时间:{}", DateTime.now());
    }

    /*
     * 天气信息推送    每天凌晨零点执行
     * 查询所有闹钟的地址，从天气表获取这些城市的天气信息，推送给每个设备
     * */
//    @Scheduled(cron = "0 0 0 * * ?")
    public void pushWeatherScheduled(){
        log.info("向设备推送天气信息定时器执行开始时间:{}", DateTime.now());

        // 查询设备地址和对应的设备硬件ID串
        List<Map<String, String>> queryList = clockService.queryCityDeviceIds();
        queryList.forEach(e -> {
            System.out.println("city：" + e.get("city"));
            String city = e.get("city");
            String deviceIds = e.get("deviceId");
            List<String> deviceIdList = Arrays.asList(deviceIds.split(","));

            // 查询该地址当天的天气信息
            Weather weather = weatherService.queryInfoByDateCity(DateUtil.getYmd(), city);

            // 将设备天气信息推送设备端
            ClockInteractionBean config = new ClockInteractionBean();
            config.setType(ClockInteractionEnum.WEATHER_PUSH.getTypeCode());
            deviceIdList.forEach(deviceId -> {
                System.out.println("deviceId：" + deviceId);
                Map<String, Object> map = new HashMap<>();
                map.put("deviceId", deviceId);
                map.put("area", weather.getLocationName());
                map.put("weather", weather.getWeatherInfo());
                config.setData(JSONObject.toJSONString(map));
                mqttMessageUtil.sendToMqtt(JSONObject.toJSONString(config), mqttConfig.getMqttDeviceTopic());
            });
        });

        log.info("向设备推送天气信息定时器执行结束时间:{}", DateTime.now());
    }

    public static void main(String[] args) {
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
//        String now = sdf.format(new Date());
//        log.info("定时预警执行时间:{}",now);

//        System.out.println(DateTime.now());

    }
}
